//
//  CedarTools.m
//  CedarSuperCloud
//
//  Created by lshenrong on 2017/11/24.
//  Copyright © 2017年 cedarhd. All rights reserved.
//

#import "CedarTools.h"
#import  "NSData+YYAdd.h"

@implementation CedarTools

+ (NSString *)replacingMiddleStarByPhone:(NSString *)phone{
    NSString *filtPhone;
    if (IsEmptyStr(phone)) {
        return @"";
    }
    NSInteger length = [phone length];
    if (length>=11) {
        filtPhone = [phone stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    }else{
        filtPhone = [phone stringByReplacingCharactersInRange:NSMakeRange(length/2, length-length/2) withString:@"****"];
    }
    return filtPhone;
}

+ (NSString *)replacingMiddleStarByName:(NSString *)name{
    if (IsEmptyStr(name) || [name length] == 1) {
        return name;
    }
    NSString *filtName;
    NSInteger length = [name length];
     NSInteger rangLength = 0;
    if (length == 2) {
        rangLength = length-1;
    }else{
        rangLength = length-2;
    }
    filtName = [name stringByReplacingCharactersInRange:NSMakeRange(1, rangLength) withString:@"*"];
    return filtName;
}



+ (NSString *)randomSixString{
    int a = arc4random() % 100000;
    NSString *randomNumber = [NSString stringWithFormat:@"%.6d", a];
    return randomNumber;
}

+ (BOOL)isPhoneNumber:(NSString *)phone{
    //NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[0678])\\d{8}$";
    NSString *pattern = @"^1+[3456789]+\\d{9}";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    return [regextestmobile evaluateWithObject:phone];
}

+ (BOOL)isVaildPassword:(NSString *)password{
    NSString *pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,18}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:password];
    return isMatch;
    
}

+ (NSString *)lastFourString:(NSString *)str{
    if([str length]<=4){
        return str;
    }
    NSInteger startIndex = [str length]-4;
    NSString *newStr = [str substringFromIndex:startIndex];
    return  newStr;
}


+ (NSString *)replaceMiddleStarExceptLastFourString:(NSString *)str{
    if([str length]<=4){
        return str;
    }
    NSInteger startIndex = [str length]-4;
    NSString *newStr = [str substringFromIndex:startIndex];
    NSMutableString *mStr =  [[NSMutableString alloc]init];
    [mStr appendString:@"**** "];
    [mStr appendString:@"**** "];
    [mStr appendString:@"**** "];
    [mStr appendString:newStr];
    return  [mStr copy];
}

+ (NSString *)idCardReplaceMiddleStarExceptLastFourString:(NSString *)str{
    NSString *filtPhone;
    if (IsEmptyStr(str)) {
        return @"";
    }
    
    NSString *string1 = [str  substringToIndex:3];
    NSString *string3 = [str substringFromIndex:str.length- 3];
    filtPhone = [NSString stringWithFormat:@"%@************%@",string1,string3];
    
//    NSInteger length = [str length];
//    if (length>=11) {
//        filtPhone = [str stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
//    }else{
//        filtPhone = [str stringByReplacingCharactersInRange:NSMakeRange(length/2, length-length/2) withString:@"****"];
//    }
    return filtPhone;
}

+ (NSString *)substringTime:(NSString *)str{
    NSArray *array = [str componentsSeparatedByString:@" "];//匹配得到的下标
    if([array count]>0){
        return array[0];
    }
    return str;
}

+ (NSString *)substringTimeToMinute:(NSString *)str{
    NSRange range =  [str rangeOfString:@":" options:NSBackwardsSearch];
    if(range.location != NSNotFound){
        NSString  *resultStr = [str substringToIndex:range.location];
        return resultStr;
    }
    return str;
}

+ (NSString *)substringTimeSecond:(NSString *)str{
    if (!str) {
        return @"";
    }
    NSRange range =  [str rangeOfString:@":" options:NSBackwardsSearch];
    if (range.location != NSNotFound){
        NSString *newStr = [str substringToIndex:range.location];//str4 = "jiemu"
        return newStr;
    }
    return str;
}

+ (NSString *)substringTimeReplacePoint:(NSString *)str{
    if (!str) {
        return @"";
    }
    NSArray *array = [str componentsSeparatedByString:@" "];//匹配得到的下标
    if([array count]>0){
        NSString *str = array[0];
        NSString *time = [str stringByReplacingOccurrencesOfString:@"-" withString:@"."];
        return time;
    }
    return str;
}


//2018-12-28 00:00:08 ->5月2日 12:25
+ (NSString *)praseTimeForMonthDayHourMintue:(NSString *)str{
    NSArray *array = [str componentsSeparatedByString:@" "];
    if([array count] == 2){
        NSString *str1 = array[0];
        NSString *str2 = array[1];
        __block NSString *yearStr = @"";
        __block NSString *monthStr = @"";
        __block NSString *dayStr = @"";
        NSArray *dateStrArray = [str1 componentsSeparatedByString:@"-"];
        [dateStrArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (idx == 0) {
                 yearStr = obj;
            }else if (idx == 1) {
                monthStr = obj;
            }else if (idx == 2) {
                dayStr = obj;
            }
        }];
        __block NSString *hourStr = @"";
        __block NSString *minuteStr = @"";
        __block NSString *secondStr = @"";
        NSArray *timeStrArray = [str2 componentsSeparatedByString:@":"];
        [timeStrArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (idx == 0) {
                hourStr = obj;
            }else if (idx == 1) {
                minuteStr = obj;
            }else if (idx == 2) {
                secondStr = obj;
            }
        }];
        NSString *time = [NSString stringWithFormat:@"%@月%@日 %@:%@",monthStr,dayStr,hourStr,minuteStr];
        return time;
    }
    return @"";
}

+ (NSString *)praseTimeForDayHourMintue:(NSString *)str{
    NSArray *array = [str componentsSeparatedByString:@" "];
    if([array count] == 2){
        NSString *str1 = array[0];
        NSString *str2 = array[1];
        __block NSString *yearStr = @"";
        __block NSString *monthStr = @"";
        __block NSString *dayStr = @"";
        NSArray *dateStrArray = [str1 componentsSeparatedByString:@"-"];
        [dateStrArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (idx == 0) {
                yearStr = obj;
            }else if (idx == 1) {
                monthStr = obj;
            }else if (idx == 2) {
                dayStr = obj;
            }
        }];
        __block NSString *hourStr = @"";
        __block NSString *minuteStr = @"";
        __block NSString *secondStr = @"";
        NSArray *timeStrArray = [str2 componentsSeparatedByString:@":"];
        [timeStrArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (idx == 0) {
                hourStr = obj;
            }else if (idx == 1) {
                minuteStr = obj;
            }else if (idx == 2) {
                secondStr = obj;
            }
        }];
        NSString *time = [NSString stringWithFormat:@"%@日 %@:%@",dayStr,hourStr,minuteStr];
        return time;
    }
    return @"";
}

//拼接字符串中 10.2%~12%  找10
+ (NSRange)findStringFromBegin:(NSString *)string key:(NSString *)key{
    NSRange startRange = [string rangeOfString:key];
    if (startRange.location != NSNotFound) {
        NSString  *resultStr = [string substringToIndex:startRange.location];
        //是否有 .
        if([resultStr containsString:@"."]){
            NSRange startRange = [string rangeOfString:@"."];
            NSRange newRange = NSMakeRange(0,startRange.location) ;
            return newRange;
        }else{
            NSRange startRange = [string rangeOfString:@"%"];
            if (startRange.location != NSNotFound) {
                NSRange newRange = NSMakeRange(0,startRange.location) ;
                return newRange;
            }
        }
    }
    NSRange newRange = NSMakeRange(0,0) ;
    return newRange;
}

//拼接字符串中 10.2%~12.25%  找12
+ (NSRange )findStringFromBackwards:(NSString *)string key:(NSString *)key{
    
    NSRange startRange = [string rangeOfString:key];
    NSRange endRange = [string rangeOfString:key options:NSBackwardsSearch];
    if (endRange.location != NSNotFound) {
        NSString  *resultStr = [string substringFromIndex:endRange.location+1];
        if([resultStr containsString:@"."]){
            NSRange range = [resultStr rangeOfString:@"."];
            NSRange newRange = NSMakeRange(startRange.location + startRange.length, range.location);
            return newRange;
        }else{
            NSRange range = [resultStr rangeOfString:@"%"];
            if (range.location != NSNotFound) {
                NSRange newRange = NSMakeRange(startRange.location + startRange.length, range.location);
                return newRange;
            }
        }
    }
    NSRange newRange = NSMakeRange(0,0) ;
    return newRange;
}


+ (NSRange)findString:(NSString *)str  start:(NSString *)start end:(NSString *)end{
    if (!str || !start || !end) {
        NSRange rang =  NSMakeRange(0, 0);
        return rang;
    }
    NSRange startRange = [str rangeOfString:start];
    NSRange endRange = [str rangeOfString:end];
    NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
    return range;
}

+ (NSRange)findStringBackwards:(NSString *)str  start:(NSString *)start end:(NSString *)end{
    if (!str || !start || !end) {
        NSRange rang =  NSMakeRange(0, 0);
        return rang;
    }
    NSRange startRange = [str rangeOfString:start options:NSBackwardsSearch];
    NSRange endRange = [str rangeOfString:end options:NSBackwardsSearch];
    NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
    return range;
}




+ (BOOL)isVaildIdentityNo:(NSString *)identityString {
    if (identityString.length != 18) return NO;
    // 正则表达式判断基本 身份证号是否满足格式
    NSString *regex2 = @"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
    NSPredicate *identityStringPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    //如果通过该验证，说明身份证格式正确，但准确性还需计算
    if(![identityStringPredicate evaluateWithObject:identityString]) return NO;
    return YES;
}

+ (NSString *)characterURL:(NSString *)sourceUrl{
    NSString *charactersToEscape = @"@$^<>(){}";//@"?!@#$^&%*+,:;='\"`<>()[]{}/\\| ";
    NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
    NSString  *newUrl = [sourceUrl stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
    return newUrl;
}

/////////////////////

+ (NSString*)encyptAES128PKCS5:(NSString*)plainText withKey:(NSString*)key{
    NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
    //length
    size_t plainTextBufferSize = [data length];
    const void*vplainText = (const void*)[data bytes];
    uint8_t*bufferPtr =NULL;
    size_t bufferPtrSize =0;
    size_t movedBytes =0;
    bufferPtrSize = (plainTextBufferSize +kCCBlockSizeAES128) & ~(kCCBlockSizeAES128-1);
    bufferPtr = malloc( bufferPtrSize *sizeof(uint8_t));
    memset((void*)bufferPtr,0x0, bufferPtrSize);
    const void*vkey = (const void*) [key UTF8String];
    //配置CCCrypt
    CCCryptorStatus ccStatus =CCCrypt(kCCEncrypt,
                                     kCCAlgorithmAES128,//3DES
                                     kCCOptionECBMode|kCCOptionPKCS7Padding,//设置模式
                                     vkey,//key
                                     kCCKeySizeAES128,
                                     nil,//偏移量，这里不用，设置为nil;不用的话，必须为nil,不可以为@“”
                                     vplainText,
                                     plainTextBufferSize,
                                     (void*)bufferPtr,
                                     bufferPtrSize,
                                     &movedBytes);
    
    if(ccStatus ==kCCSuccess) {
        NSData*myData = [NSData dataWithBytes:(const char*)bufferPtr length:(NSUInteger)movedBytes];
        NSString *str =  [myData base64EncodedString];
        if (bufferPtr) {
            free(bufferPtr);
        }
        return str;
    }
    if (bufferPtr) {
        free(bufferPtr);
    }
    return nil;
}


+ (NSString*)decryptAES128PKCS5:(NSString*)plainText withKey:(NSString*)key{
    NSData *data = [NSData   dataWithBase64EncodedString:plainText];
    size_t plainTextBufferSize = [data length];
    const void*vplainText = (const void*)[data bytes];
    uint8_t*bufferPtr =NULL;
    size_t bufferPtrSize =0;
    size_t movedBytes =0;
    bufferPtrSize = (plainTextBufferSize +kCCBlockSizeAES128) & ~(kCCBlockSizeAES128-1);
    bufferPtr = malloc( bufferPtrSize *sizeof(uint8_t));
    memset((void*)bufferPtr,0x0, bufferPtrSize);
    const void*vkey = (const void*) [key UTF8String];
    //配置CCCrypt
    CCCryptorStatus ccStatus =CCCrypt(kCCDecrypt,
                                      kCCAlgorithmAES128,//3DES
                                      kCCOptionECBMode|kCCOptionPKCS7Padding,//设置模式
                                      vkey,//key
                                      kCCKeySizeAES128,
                                      nil,//偏移量，这里不用，设置为nil;不用的话，必须为nil,不可以为@“”
                                      vplainText,
                                      plainTextBufferSize,
                                      (void*)bufferPtr,
                                      bufferPtrSize,
                                      &movedBytes);
    if(ccStatus ==kCCSuccess) {
        NSData*myData = [NSData dataWithBytes:(const char*)bufferPtr length:(NSUInteger)movedBytes];
        NSString *result =[[ NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
        if (bufferPtr) {
            free(bufferPtr);
        }
        return result;
    }
    if (bufferPtr) {
        free(bufferPtr);
    }
    return nil;
}


+ (NSString *)dictToJsonStr:(NSDictionary *)dict{
    NSString *jsonString = @"";
    if([NSJSONSerialization isValidJSONObject:dict]){
        NSError *error;
        NSData*jsonData = [NSJSONSerialization dataWithJSONObject:dict
                                                          options:NSJSONWritingPrettyPrinted
                                                            error:&error];
        jsonString = [[NSString alloc] initWithData:jsonData
                                           encoding:NSUTF8StringEncoding];
        if(error){
           CLog(@"dictToJsonStr Error:%@", error);
        }
        
        if ([jsonString length] == 0) {
            return @"";
        }
        NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
        //NSRange range = {0,jsonString.length};
        //去掉字符串中的空格
        //[mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
        NSRange range2 = {0,mutStr.length};
        //去掉字符串中的换行符
        [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
        jsonString = mutStr;
      //  jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];  //去除掉首尾的空白字符和换行字符
     //   [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    }
    return jsonString;
}

+ (NSString *)substring:(NSString *)str sign:(NSString *)signStr{
     NSString *resultStr = @"";
    if (IsEmptyStr(str) || IsEmptyStr(signStr)) {
        return resultStr;
    }
    NSRange range = [str rangeOfString:signStr];
    if (range.location != NSNotFound) {
        resultStr = [str substringToIndex:range.location];
    }
    return resultStr;
}

+ (NSString *)subStringWithPercent:(NSString *)str sign:(NSString *)signStr{
    NSString *resultStr = @"";
    if (IsEmptyStr(str) || IsEmptyStr(signStr)) {
        return resultStr;
    }
    NSRange range = [str rangeOfString:signStr];
    if (range.location != NSNotFound) {
        resultStr = [str substringToIndex:range.location];
    }else{
         NSRange range1 = [str rangeOfString:@"%"];
        if (range1.location != NSNotFound) {
           resultStr = [str substringToIndex:range1.location];
        }else{
            resultStr = str;
        }
    }
    return resultStr;
}

+ (NSString *)splitFomateJsonWithDictionary:(NSDictionary *)dict {
    NSMutableString *mStr = [NSMutableString stringWithString:@"{"];
    NSArray *keys = [dict allKeys];
    for (NSInteger i =0; i<keys.count ; i++) {
        
        NSString *key = keys[i];
        NSString *newkey = [NSString stringWithFormat:@"\"%@\"",key];

        NSString *value = [dict objectForKey:key];
        NSString *newValue = [NSString stringWithFormat:@"\"%@\"",value];
        
        NSString *string = [NSString stringWithFormat:@"%@:%@",newkey,newValue];
        
        [mStr appendString:string];
        if (i < keys.count-1) {
            [mStr appendString:@","];
        }
    }
    [mStr appendString:@"}"];
    return mStr;
}

+ (NSString *)replaceUnicode:(NSString *)unicodeStr{
    return  @" ";
}

+ (BOOL)isValidateIdentityCardNo:(NSString *)identityString{
    if (identityString.length != 18) return NO;
    // 正则表达式判断基本 身份证号是否满足格式
    NSString *regex = @"^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X|x)$";
     //  NSString *regex = @"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
    NSPredicate *identityStringPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    //如果通过该验证，说明身份证格式正确，但准确性还需计算
    if(![identityStringPredicate evaluateWithObject:identityString]) return NO;
    //** 开始进行校验 *//
    //将前17位加权因子保存在数组里
    NSArray *idCardWiArray = @[@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2"];
    
    //这是除以11后，可能产生的11位余数、验证码，也保存成数组
    NSArray *idCardYArray = @[@"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];
    
    //用来保存前17位各自乖以加权因子后的总和
    NSInteger idCardWiSum = 0;
    for(int i = 0;i < 17;i++) {
        NSInteger subStrIndex = [[identityString substringWithRange:NSMakeRange(i, 1)] integerValue];
        NSInteger idCardWiIndex = [[idCardWiArray objectAtIndex:i] integerValue];
        idCardWiSum+= subStrIndex * idCardWiIndex;
    }
    
    //计算出校验码所在数组的位置
    NSInteger idCardMod=idCardWiSum%11;
    //得到最后一位身份证号码
    NSString *idCardLast= [identityString substringWithRange:NSMakeRange(17, 1)];
    //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
    if(idCardMod==2) {
        NSString *str =  [idCardLast lowercaseString];
        if(![str isEqualToString:@"x"]) {
            return NO;
        }
    }
    else{
        //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
        if(![idCardLast isEqualToString: [idCardYArray objectAtIndex:idCardMod]]) {
            return NO;
        }
    }
    return YES;
}

+ (BOOL)validateIDCardNumber:(NSString *)value {
    value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSInteger length =0;
    if (!value) {
        return NO;
    }else {
        length = value.length;
        //不满足15位和18位，即身份证错误
        if (length !=15 && length !=18) {
            return NO;
        }
    }
    // 省份代码
    NSArray *areasArray = @[@"11",@"12", @"13",@"14", @"15",@"21", @"22",@"23", @"31",@"32", @"33",@"34", @"35",@"36", @"37",@"41", @"42",@"43", @"44",@"45", @"46",@"50", @"51",@"52", @"53",@"54", @"61",@"62", @"63",@"64", @"65",@"71", @"81",@"82", @"91"];
    
    // 检测省份身份行政区代码
    NSString *valueStart2 = [value substringToIndex:2];
    BOOL areaFlag =NO; //标识省份代码是否正确
    for (NSString *areaCode in areasArray) {
        if ([areaCode isEqualToString:valueStart2]) {
            areaFlag =YES;
            break;
        }
    }
    
    if (!areaFlag) {
        return NO;
    }
    
    NSRegularExpression *regularExpression;
    NSUInteger numberofMatch;
    
    int year =0;
    //分为15位、18位身份证进行校验
    switch (length) {
        case 15:
            //获取年份对应的数字
            year = [value substringWithRange:NSMakeRange(6,2)].intValue +1900;
            
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                //创建正则表达式 NSRegularExpressionCaseInsensitive：不区分字母大小写的模式
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$"
                                                                        options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$"
                                                                        options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
            }
            //使用正则表达式匹配字符串 NSMatchingReportProgress:找到最长的匹配字符串后调用block回调
            numberofMatch = [regularExpression numberOfMatchesInString:value
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, value.length)];
            
            if(numberofMatch >0) {
                return YES;
            }else {
                return NO;
            }
        case 18:
            year = [value substringWithRange:NSMakeRange(6,4)].intValue;
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$" options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$" options:NSRegularExpressionCaseInsensitive error:nil];//测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:value
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, value.length)];
            
            
            if(numberofMatch >0) {
                //1：校验码的计算方法 身份证号码17位数分别乘以不同的系数。从第一位到第十七位的系数分别为：7－9－10－5－8－4－2－1－6－3－7－9－10－5－8－4－2。将这17位数字和系数相乘的结果相加。
                
                int S = [value substringWithRange:NSMakeRange(0,1)].intValue*7 + [value substringWithRange:NSMakeRange(10,1)].intValue *7 + [value substringWithRange:NSMakeRange(1,1)].intValue*9 + [value substringWithRange:NSMakeRange(11,1)].intValue *9 + [value substringWithRange:NSMakeRange(2,1)].intValue*10 + [value substringWithRange:NSMakeRange(12,1)].intValue *10 + [value substringWithRange:NSMakeRange(3,1)].intValue*5 + [value substringWithRange:NSMakeRange(13,1)].intValue *5 + [value substringWithRange:NSMakeRange(4,1)].intValue*8 + [value substringWithRange:NSMakeRange(14,1)].intValue *8 + [value substringWithRange:NSMakeRange(5,1)].intValue*4 + [value substringWithRange:NSMakeRange(15,1)].intValue *4 + [value substringWithRange:NSMakeRange(6,1)].intValue*2 + [value substringWithRange:NSMakeRange(16,1)].intValue *2 + [value substringWithRange:NSMakeRange(7,1)].intValue *1 + [value substringWithRange:NSMakeRange(8,1)].intValue *6 + [value substringWithRange:NSMakeRange(9,1)].intValue *3;
                
                //2：用加出来和除以11，看余数是多少？余数只可能有0－1－2－3－4－5－6－7－8－9－10这11个数字
                int Y = S %11;
                NSString *M =@"F";
                NSString *JYM =@"10X98765432";
                M = [JYM substringWithRange:NSMakeRange(Y,1)];// 3：获取校验位
                //4：检测ID的校验位
                if ([M isEqualToString:[value substringWithRange:NSMakeRange(17,1)]]) {
                    return YES;
                }else {
                    return NO;
                }
                
            }else {
                return NO;
            }
        default:
            return NO;
    }
}


////////////////////////   价格字符串    ////////////////////////

#pragma mark - compute

+ (NSString *)number:(NSString *)number1 byAdd:(NSString *)number2{
    NSDecimalNumber *source1 = [NSDecimalNumber decimalNumberWithString:number1];
    NSDecimalNumber *source2 = [NSDecimalNumber decimalNumberWithString:number2];
    NSDecimalNumber *result = [source1 decimalNumberByAdding:source2];
    NSString *resultStr = [NSString stringWithFormat:@"%@",result];
    return resultStr;
}

+ (NSString *)number:(NSString *)number1 byReduce:(NSString *)number2{
    NSDecimalNumber *source1 = [NSDecimalNumber decimalNumberWithString:number1];
    NSDecimalNumber *source2 = [NSDecimalNumber decimalNumberWithString:number2];
    NSDecimalNumber *result = [source1 decimalNumberBySubtracting:source2];
    NSString *resultStr = [NSString stringWithFormat:@"%@",result];
    return resultStr;
}



+ (NSComparisonResult)number:(NSString *)number1 compareNumber:(NSString *)number2{
    NSDecimalNumber *source1 = [NSDecimalNumber decimalNumberWithString:number1];
    NSDecimalNumber *source2 = [NSDecimalNumber decimalNumberWithString:number2];
    NSComparisonResult result = [source1 compare:source2];
    return result;
}




+ (NSString *)number:(NSString *)number1 byMultiplying:(NSString *)number2{
    NSDecimalNumberHandler *handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundBankers
                                                                                             scale:4
                                                                                  raiseOnExactness:NO
                                                                                   raiseOnOverflow:NO
                                                                                  raiseOnUnderflow:NO
                                                                               raiseOnDivideByZero:YES];
    
    NSDecimalNumber *source1 = [NSDecimalNumber decimalNumberWithString:number1];
    NSDecimalNumber *source2 = [NSDecimalNumber decimalNumberWithString:number2];
    NSDecimalNumber *result = [source1 decimalNumberByMultiplyingBy:source2 withBehavior:handler];
    NSString *resultStr = [NSString stringWithFormat:@"%@",result];
    return resultStr;
}


+ (NSString *)number:(NSString *)number1 byDividing:(NSString *)number2{
    NSDecimalNumberHandler *handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundBankers
                                                                                             scale:4
                                                                                  raiseOnExactness:NO
                                                                                   raiseOnOverflow:NO
                                                                                  raiseOnUnderflow:NO
                                                                               raiseOnDivideByZero:YES];
    NSDecimalNumber *source1 = [NSDecimalNumber decimalNumberWithString:number1];
    NSDecimalNumber *source2 = [NSDecimalNumber decimalNumberWithString:number2];
    NSDecimalNumber *result = [source1 decimalNumberByDividingBy:source2 withBehavior:handler];
    NSString *resultStr = [NSString stringWithFormat:@"%@",result];
    return resultStr;
}



+ (NSDecimalNumber *)number1:(NSString *)number1 byReduceNumber2:(NSString *)number2{
    NSDecimalNumber *source1 = [NSDecimalNumber decimalNumberWithString:number1];
    NSDecimalNumber *source2 = [NSDecimalNumber decimalNumberWithString:number2];
    NSDecimalNumber *result = [source1 decimalNumberBySubtracting:source2];
    return result;
}

+ (NSDecimalNumber *)number1:(NSString *)number1 byMultiplyingNumber2:(NSString *)number2{
    NSDecimalNumber *source1 = [NSDecimalNumber decimalNumberWithString:number1];
    NSDecimalNumber *source2 = [NSDecimalNumber decimalNumberWithString:number2];
    NSDecimalNumber *result = [source1 decimalNumberByMultiplyingBy:source2];
    return result;
}


//
//+ (NSString *)dealWithNumWanWithString:(NSString *)string{
//    if (IsEmptyStr(string)) {
//        return @"0.00";
//    }
//    NSDecimalNumber *numberA = [NSDecimalNumber decimalNumberWithString:string];
//    NSDecimalNumber *numberB =  [NSDecimalNumber decimalNumberWithString:@"10000"];;
//    //NSDecimalNumberBehaviors对象的创建  参数 1.RoundingMode 一个取舍枚举值 2.scale 处理范围 3.raiseOnExactness  精确出现异常是否抛出原因 4.raiseOnOverflow  上溢出是否抛出原因  4.raiseOnUnderflow  下溢出是否抛出原因  5.raiseOnDivideByZero  除以0是否抛出原因。
//    NSDecimalNumberHandler *roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundDown scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
//    NSDecimalNumber *numResult = [numberA decimalNumberByDividingBy:numberB withBehavior:roundingBehavior];
//    NSString *strResult = [numResult stringValue];
//    return strResult;
//}

//输入的金额是否满足最低 递增 规则
+ (BOOL)isAllowConditionMoney:(NSString *)money minAmount:(NSString *)min increaseAmount:(NSString *)increase{
    NSDecimalNumber *moneyNumbr = [NSDecimalNumber decimalNumberWithString:money];
    NSDecimalNumber *minNumber = [NSDecimalNumber decimalNumberWithString:min];
    NSDecimalNumber *increaseNumber = [NSDecimalNumber decimalNumberWithString:increase];
    NSComparisonResult result = [moneyNumbr compare:minNumber];
    if (result == NSOrderedAscending) {//
        return NO;
    }
    //输入金额减去最小金额  能整除  递增 就表示满足条件
    
    NSDecimalNumberHandler *handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundBankers
                                                                                             scale:2
                                                                                  raiseOnExactness:NO
                                                                                   raiseOnOverflow:NO
                                                                                  raiseOnUnderflow:NO
                                                                               raiseOnDivideByZero:YES];
    
    NSDecimalNumber *resultNumber = [moneyNumbr decimalNumberBySubtracting:minNumber withBehavior:handler];
    BOOL result22 = [self judgeDivisibleWithFirstNumber:resultNumber.doubleValue andSecondNumber:increaseNumber.doubleValue];
    return result22;
}


/**
 *  判断两个浮点数是否整除
 *
 *  @param firstNumber  第一个浮点数(被除数)
 *  @param secondNumber 第二个浮点数(除数,不能为0)
 *
 *  @return 返回值可判定是否整除
 */
+ (BOOL)judgeDivisibleWithFirstNumber:(CGFloat)firstNumber andSecondNumber:(CGFloat)secondNumber {
    // 默认记录为整除
    BOOL isDivisible = YES;
    
    if (secondNumber == 0) {
        return NO;
    }
    
    CGFloat result = firstNumber / secondNumber;
    NSString * resultStr = [NSString stringWithFormat:@"%f", result];
    NSRange range = [resultStr rangeOfString:@"."];
    if (range.location == NSNotFound) {
        return NO;
    }
    
    
    NSString * subStr = [resultStr substringFromIndex:range.location + 1];
    
    for (NSInteger index = 0; index < subStr.length; index ++) {
        unichar ch = [subStr characterAtIndex:index];
        
        // 后面的字符中只要有一个不为0，就可判定不能整除，跳出循环
        if ('0' != ch) {
            //            NSLog(@"不能整除");
            isDivisible = NO;
            break;
        }
    }
    
    // NSLog(@"可以整除");
    return isDivisible;
}


+ (NSString *)thousandFormat:(NSString *)text{
    if(IsEmptyStr(text) || [text isEqualToString:@"0"]){
        return @"0";
    }
    if ([text doubleValue] < 1) {
        return  [NSString stringWithFormat:@"%.2f",text.doubleValue];
    }
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setPositiveFormat:@",###.00"];
    numberFormatter.roundingMode = NSNumberFormatterRoundDown;
    NSString *numberFormatterStr = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:[text doubleValue]]];
    return numberFormatterStr;
}

+ (NSString *)thousandFormatNoDecimalPoint:(NSString *)text{
    if(IsEmptyStr(text) || [text isEqualToString:@"0"]){
        return @"0";
    }
    if ([text doubleValue] < 1) {
        return  [NSString stringWithFormat:@"%.2f",text.doubleValue];
    }
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setPositiveFormat:@",###"];
    NSString *numberFormatterStr = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:[text doubleValue]]];
    return numberFormatterStr;
}

+ (NSString *)moneyFormatForTwoDecimalNumString:(NSString *)text{
    if (IsEmptyStr(text)|| [text isEqualToString:@"0"]) {
        return @"0.00";
    }
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setPositiveFormat:@"0.00"];
    NSString *numberFormatterStr = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:[text doubleValue]]];
    return numberFormatterStr;
}


+ (NSString *)moneyNotRounding:(NSString *)money  afterPoint:(NSInteger)position{
    NSDecimalNumberHandler* roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundDown scale:position raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
    NSDecimalNumber *ouncesDecimal;
    NSDecimalNumber *roundedOunces;
    ouncesDecimal = [[NSDecimalNumber alloc] initWithString:money];
    roundedOunces = [ouncesDecimal decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
    return [NSString stringWithFormat:@"%@",roundedOunces];
}

//格式化2位小数，没有补0 不四5入
+ (NSString *)moneyFormateAfterTwoPoint:(NSString *)money{
    if (IsEmptyStr(money) || [money doubleValue] == 0) {
        return @"0.00";
    }
    NSNumber *number = [NSNumber numberWithString:money];
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.roundingMode = NSNumberFormatterRoundDown;
    formatter.maximumFractionDigits = 2;
    // 小数位最少位数
    formatter.minimumFractionDigits = 2;
    formatter.minimumIntegerDigits = 1;
    NSString *formateMoney = [formatter stringFromNumber:number];
    return formateMoney;
}

+ (NSString *)thousandFormatWithNoDecimalPoint:(NSString *)text{
    if(IsEmptyStr(text) || [text isEqualToString:@"0"]){
        return @"0";
    }
    if ([text doubleValue] < 1) {
         return @"0";
    }
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setPositiveFormat:@",###"];
    NSString *numberFormatterStr = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:[text doubleValue]]];
    return numberFormatterStr;
}



/**
 转化为万 无单位 10000->1  100->0.0100
 */
+ (NSString *)thousandFormatForTenThousandNoDecimalPoint:(NSString *)text{
    if(IsEmptyStr(text) || [text isEqualToString:@"0"]){
        return @"0";
    }
    if ([text doubleValue] < 10000) {
        NSString *str =    [self number:text byDividing:@"10000"];
        return  str;
    }
    NSString *str =    [self number:text byDividing:@"10000"];
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setPositiveFormat:@",###"];
    NSString *numberFormatterStr = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:[str doubleValue]]];
    return numberFormatterStr;
}


/**
 格式化万 带有单位 <10000时 显示元
 */
+ (NSString *)thousandFormatForTenThousandWithUnitNoDecimalPoint:(NSString *)text{
    if(IsEmptyStr(text) || [text isEqualToString:@"0"]){
        return @"0元";
    }
    if ([text doubleValue] < 10000) {
        NSString  *restult = [self thousandFormatWithNoDecimalPoint:text];
        NSString  *str = [NSString stringWithFormat:@"%@元",restult];
        return  str;
    }
    NSString *str =    [self number:text byDividing:@"10000"];
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setPositiveFormat:@",###"];
    NSString *numberFormatterStr = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:[str doubleValue]]];
    NSString  *restult = [NSString stringWithFormat:@"%@万",numberFormatterStr];
    return restult;
}


+ (NSString *)moneyFormateRemoveDecimalPointZero:(NSString *)money{
    if (IsEmptyStr(money) || [money doubleValue] == 0) {
        return @"0";
    }
    NSNumber *number = [NSNumber numberWithString:money];
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.roundingMode = NSNumberFormatterRoundDown;
    formatter.maximumFractionDigits = 5;
    // 小数位最少位数
    //formatter.minimumFractionDigits = 2;
    formatter.minimumFractionDigits = 0;
    formatter.minimumIntegerDigits = 1;
    NSString *formateMoney = [formatter stringFromNumber:number];
    return formateMoney;
}

+ (NSString *)emptyStringToZero:(NSString *)str{
    if (IsEmptyStr(str)) {
        return @"0";
    }
    return str;
}



#pragma mark - image compress
/*
- (UIImage *)imageCompressedImageToLimitSizeOfKB:(CGFloat)kb image:(UIImage*)sourceImage{
    if(!sourceImage){
        return nil;
    }
    NSData * imageData = UIImageJPEGRepresentation(sourceImage,1);
    NSUInteger length = [imageData length] /1024;
#ifdef DEBUG
    NSLog(@"压缩前大小imageData = %zdK，size %@",length, NSStringFromCGSize(sourceImage.size));
#endif
    if(length >kb ){
        float compressedRatio = kb / length;
        UIImage *image = UIImageJPEGRepresentation(image, compressedRatio);
        return
        
    }else{
        return imageData;
    }
}*/


- (UIImage *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size{
    if (!image) {
        return nil;
    }
    NSData * data = UIImageJPEGRepresentation(image, 1.0);
    CGFloat dataKBytes = data.length/1024.0;
    CGFloat maxQuality = 0.9f;
    CGFloat lastData = dataKBytes;
    while (dataKBytes > size && maxQuality > 0.01f) {
        maxQuality = maxQuality - 0.01f;
        data = UIImageJPEGRepresentation(image, maxQuality);
        dataKBytes = data.length / 1024.0;
        if (lastData == dataKBytes) {
            break;
            
        }else{
            lastData = dataKBytes;
        }
    }
    UIImage *newImage = [UIImage imageWithData: data];
    return newImage;
}

/*
 - (void)saveImage:(UIImage *)image{
     //png格式
     NSData *imagedata= UIImageJPEGRepresentation(image,1);
     //JEPG格式
     //NSData *imagedata=UIImageJEPGRepresentation(m_imgFore,1.0);
     NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
     NSString *documentsDirectory = [paths objectAtIndex:0];
     NSString *savedImagePath=[documentsDirectory stringByAppendingPathComponent:@"saveTest.jpg"];
     [imagedata writeToFile:savedImagePath atomically:YES];
 }
*/

@end
